package org.bot.plugin.data.event;

import com.alibaba.fastjson.JSONObject;
import org.bot.api.event.DataStorage;
import org.bot.api.event.EventName;
import org.bot.api.event.Events;
import org.bot.api.flow.FlowNode;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 沧月
 * @create 0028 2023/9/28 14:21
 * @description <JSON对象数据解析获取>
 */
@Component
@EventName("对象解析")
public class DataObjectAnalysis implements Events {
    @Override
    public Object exec(FlowNode note, DataStorage data) {
        String key = note.getArg();
        if (key == null) {
            return null;
        }
        String dataIndex = note.getDataIndex();
        if (dataIndex == null) {
            return null;
        }

        if (!data.containsKey(dataIndex)) {
            return null;
        }

        Object o = data.get(dataIndex);
        if (o instanceof JSONObject) {
            JSONObject value = (JSONObject) o;
            String[] keys = key.split("\\.");
            if (keys.length == 1) {
                return value.get(key);
            }

            JSONObject tmp = value;
            for (int i = 0; i < keys.length; i++) {
                if (i + 1 >= keys.length) {
                    return tmp.get(keys[i]);
                }
                if (tmp.get(keys[i]) == null || !(tmp.get(keys[i]) instanceof JSONObject)) {
                    return null;
                }
                tmp = (JSONObject) tmp.get(keys[i]);
            }
        }
        return null;
    }
}
